<template>
    <div>
        <!-- 共用头部组件 -->
        <common-header
            headerTitle="马上拼团"
            :hasBack="true"
            :hasHome="true"
        ></common-header>
        <!-- 共用头部组件 -->

        <!-- 共用页面滚动组件 -->
        <common-scroll
            :scrollStyle="scrollStyle"
            :isLoadMore="false"
        >

            <div class="goods-info-box">
                <div class="goods-img-box">
                    <img
                        class="goods-img"
                        :src="goodsInfo.imgs[0].title_img"
                    />
                </div>
                <div class="goods-info">
                    <div class="goods-name">{{goodsInfo.title}}</div>
                    <div class="goods-detail">{{goodsInfo.title_sub}}</div>
                    <div class="goods-price-box">
                        <div class="goods-now-price">{{activityInfo.member_count}}人团特享：{{activityInfo.price_master | currency}}</div>
                        <div class="goods-normal-price">￥{{goodsInfo.price_market | currency}}</div>
                    </div>
                </div>
            </div>

            <div class="group-buy-rules">
                <div class="rules-label">{{activityInfo.member_count}}人团</div>
                <div class="rules-detail">该商品所有用户均可开团，参团每人只有1次机会</div>
            </div>

            <div
                class="group-info-box"
                v-if="fullGroup"
            >
                <div class="group-people-num">还差<span>{{activityInfo.member_count-groupList.length}}</span>人成团，快来加入吧！</div>
                <div
                    class="group-time"
                    ref="groupTime"
                >
                    剩余
                    <span v-show="remainDay>0">{{remainDay}}天</span>
                    <span class="time-label"><span v-show="remainHour<10">0</span>{{remainHour}}</span>
                    :
                    <span class="time-label"><span v-show="remainMinute<10">0</span>{{remainMinute}}</span>
                    :
                    <span class="time-label"><span v-show="remainSecond<10">0</span>{{remainSecond}}</span>
                    结束
                </div>
                <div class="group-tips">马上分享，邀请好友成团</div>
                <div class="group-rules">（参团每人只有1次机会）</div>
                <div
                    class="invite-group-btn"
                    :class="isOverTime == true?'overTime':''"
                    v-if="userInfo.id == groupInfo.user_id || isJoin == true"
                    @click="shareShow"
                >邀请好友</div>
                <div
                    class="go-join-btn"
                    :class="isOverTime == true?'overTime':''"
                    v-else
                    @click="goJoinGroup"
                >马上参团</div>
            </div>

            <div class="group-join-info">
                <div class="group-people-box">
                    <div class="group-item">
                        <img
                            class="group-item-img"
                            :src="groupList[0].face"
                        />
                        <div class="group-leader-label">团长</div>
                    </div>
                    <div class="group-item">
                        <img
                            class="group-item-img"
                            :src="groupList.length>1?groupList[1].face:defaultFace"
                        />
                        <div class="group-member-label">新用户</div>
                    </div>
                    <div
                        class="group-item"
                        v-if="activityInfo.member_count == 3"
                    >
                        <img
                            class="group-item-img"
                            :src="groupList.length>2?groupList[2].face:defaultFace"
                        />
                        <div class="group-member-label">新用户</div>
                    </div>
                </div>
                <div class="group-create-time">
                    <div class="create-time-title">开团时间</div>
                    <div class="create-time-detail">{{groupInfo.begin_time}}</div>
                </div>
                <div class="group-create-rule">参团每人只有一次机会，拼团人数不足，逾期将自动撤团，并返还拼团次数。</div>
            </div>

        </common-scroll>
        <!-- 共用页面滚动组件 -->

        <!-- 分享引导组件 -->
        <div
            class="share-bg"
            v-if="shareTips"
            @click.prevent.self="shareTips = false"
        >
            <div
                class="share-main"
                ref="imageWrapper"
            >
                <slot>
                    <img
                        class="share-main-bg"
                        src="@/assets/images/groupBuy/group-invite-bg.jpg"
                    />
                    <div class="user-info-box">
                        <img
                            class="user-img"
                            :src="'data:image/png;base64,'+headerImgUrl"
                        />
                        <div class="user-info">
                            <div class="user-name-id">{{decodeURI(userInfo.nick_name)}} <span class="id-color">ID：{{userInfo.id}}</span></div>
                            <div class="user-tips">快来和我一起拼团</div>
                        </div>
                    </div>
                    <div class="share-img-box">
                        <img
                            class="share-img"
                            :src="'data:image/png;base64,'+shareImgUrl"
                            @load="imgLoad"
                        />
                        <img
                            class="share-tips-img"
                            src="@/assets/images/groupBuy/group-invite-tips.png"
                        />
                        <div class="share-tips">{{activityInfo.member_count-groupList.length}}</div>
                    </div>
                    <div class="qrcode-box">
                        <div
                            class="qrcode"
                            ref="qrCodeUrl"
                        ></div>
                    </div>
                </slot>
            </div>
            <div class="share-tips">长按图片可发送给好友一起参与~</div>
        </div>
        <!-- 分享引导组件 -->

        <div
            class="loading-bg"
            v-show="shareLoading"
        >
            <img
                class="loading-img"
                src="@/assets/images/home/loading.gif"
            />
            <div class="loading-tips">分享图片生成中...</div>
        </div>

        <div
            class="invite-tips-box"
            v-if="inviteShow"
        >
            <img
                class="invite-tips-img"
                src="@/assets/images/groupBuy/invite-tips-img.png"
            />
            <img
                class="invite-tips-know"
                src="@/assets/images/groupBuy/invite-tips-know.png"
                @click="inviteShow = false"
            />
        </div>

        <!-- 绑定手机组件 -->
        <bind-phone
            :bindPhone="bindPhone"
            @closeBindPhone="closeBindPhone"
        ></bind-phone>
        <!-- 绑定手机组件 -->
    </div>
</template>

<script>
var interval
import CommonHeader from '@/components/Header'
import CommonScroll from '@/components/Scroll'
import BindPhone from '@/components/BindPhone'
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
import wx from 'weixin-js-sdk'
export default {
    name: 'JoinGroup',
    components: {
        CommonHeader,
        CommonScroll,
        BindPhone
    },
    data() {
        return {
            scrollStyle: {
                top: '1.11rem',
                left: '0',
                right: '0',
                bottom: '0'
            },
            remainDay: 0,
            remainHour: 0,
            remainMinute: 0,
            remainSecond: 0,
            isOverTime: false,
            inviteShow: false,
            userInfo: '',
            groupInfo: '',
            goodsInfo: '',
            activityInfo: '',
            groupList: [],
            defaultFace: require('@/assets/images/groupBuy/group-empty-img.png'),
            shareTips: false,
            bindPhone: false,
            shareImgUrl: '',
            headerImgUrl: '',
            shareLoading: false,
            bindPhone: false,
            fullGroup: false,
            isJoin: false,
            time: ''
        }
    },
    mounted() {
        this.getUserInfo()
        this.getGroupInfo()
        this.getIsJoin()
    },
    methods: {
        getWxConfig() {
            const that = this
            this.axios.post('/api/jsconfig.json').then(res => {
                const data = res.data
                if (data.status == 1) {
                    let routeHost = window.location.origin
                    let routeHref = window.location.href.split('#')[0]
                    let routePath = encodeURIComponent(
                        window.location.href.split('#')[1]
                    )
                    wx.config(data.data)
                    wx.ready(function() {
                        if (typeof wx.updateAppMessageShareData == 'function') {
                            wx.updateAppMessageShareData({
                                title:
                                    '百领商城三人团：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                success: function() {
                                    // 设置成功
                                }
                            })
                        } else {
                            wx.onMenuShareAppMessage({
                                title:
                                    '百领商城三人团：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                type: '', // 分享类型,music、video或link，不填默认为link
                                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                                success: function() {
                                    // 用户点击了分享后执行的回调函数
                                }
                            })
                        }
                        if (typeof wx.onMenuShareTimeline == 'function') {
                            wx.onMenuShareTimeline({
                                title:
                                    '百领商城三人团：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                success: function() {
                                    // 设置成功
                                }
                            })
                        } else {
                            wx.onMenuShareTimeline({
                                title:
                                    '百领商城三人团：' + that.goodsInfo.title, // 分享标题
                                desc: that.goodsInfo.title_sub, // 分享描述
                                link: routeHref + '&route=' + routePath, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: that.goodsInfo.imgs[0].title_img, // 分享图标
                                success: function() {
                                    // 用户点击了分享后执行的回调函数
                                }
                            })
                        }
                    })
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
        },
        getUserInfo() {
            this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
            if (this.userInfo.face == '') {
                this.headerImgUrl = null
                return
            }
            this.toBase64(this.userInfo.face, 'headerImgUrl')
        },
        getGroupInfo() {
            let postData = this.qs.stringify({
                id: this.$route.query.groupId
            })
            this.axios
                .post('/api/group_buy/group_info.json', postData)
                .then(res => {
                    const data = res.data
                    if (data.status == 1) {
                        if (data.data.group.status == 0) {
                            this.fullGroup = true
                            this.time = setInterval(this.getTime, 1000)
                        }
                        this.groupInfo = data.data.group
                        this.goodsInfo = data.data.goods
                        this.activityInfo = data.data.activity
                        this.groupList = data.data.item_list
                        this.getWxConfig()
                        this.toBase64(
                            this.goodsInfo.imgs[0].title_img,
                            'shareImgUrl'
                        )
                    } else {
                        this.commonDialog.alert('提示', data.msg)
                    }
                })
        },
        getIsJoin() {
            if (this.userInfo == '' || this.groupList.length == 0) {
                setTimeout(this.getIsJoin, 200)
            } else {
                this.groupList.forEach(e => {
                    if (e.user_id == this.userInfo.id) {
                        this.isJoin = true
                    }
                })
            }
        },
        goJoinGroup() {
            const that = this
            if (
                this.userInfo.mobile_phone == '' ||
                this.userInfo.mobile_phone == null
            ) {
                this.bindPhone = true
                return
            }
            let postData = this.qs.stringify({
                group_id: this.$route.query.groupId
            })
            this.axios
                .post('/api/group_buy/join_group.json', postData)
                .then(res => {
                    const data = res.data
                    if (data.status == 1) {
                        this.commonDialog.alert(
                            '提示',
                            '恭喜您，参团成功！',
                            function() {
                                that.$router.push('/myGroup')
                            }
                        )
                    } else {
                        this.commonDialog.alert('提示', data.msg)
                    }
                })
        },
        closeBindPhone() {
            this.bindPhone = false
        },
        getTime() {
            let today = new Date(), //当前时间
                h = today.getHours(),
                m = today.getMinutes(),
                s = today.getSeconds()
            let stopTime = new Date(this.groupInfo.end_time.replace(/-/g, '/')), //结束时间
                stopH = stopTime.getHours(),
                stopM = stopTime.getMinutes(),
                stopS = stopTime.getSeconds()
            let remainTime = stopTime.getTime() - today.getTime()
            if (remainTime < 0) {
                this.$refs.groupTime.innerHTML = '已结束'
                this.isOverTime = true
                clearInterval(this.time)
                return
            }
            this.remainDay = parseInt(remainTime / (60 * 60 * 24 * 1000)) //转换为天
            let remainTimeD =
                parseInt(remainTime) -
                parseInt(this.remainDay * 60 * 60 * 24 * 1000) //除去天的毫秒数
            this.remainHour = parseInt(remainTimeD / (60 * 60 * 1000)) //除去天的毫秒数转换成小时
            let remainTimeH = remainTimeD - this.remainHour * 60 * 60 * 1000 //除去天、小时的毫秒数
            this.remainMinute = parseInt(remainTimeH / (60 * 1000)) //除去天的毫秒数转换成分钟
            let remainTimeM = remainTimeH - this.remainMinute * 60 * 1000 //除去天、小时、分的毫秒数
            this.remainSecond = parseInt(
                (remainTime -
                    this.remainDay * 60 * 60 * 24 * 1000 -
                    this.remainHour * 60 * 60 * 1000 -
                    this.remainMinute * 60 * 1000) /
                    1000
            ) //除去天、小时、分的毫秒数转化为秒
        },
        imgLoad() {
            this.toImage()
        },
        shareShow() {
            this.shareLoading = true
            if (this.shareImgUrl == '' || this.headerImgUrl == '') {
                setTimeout(this.shareShow, 500)
            } else {
                const that = this
                this.shareTips = true
                this.$nextTick(() => {
                    that.makeCode()
                })
            }
        },
        makeCode() {
            let routeHref = window.location.href
            let qrcode = new QRCode(this.$refs.qrCodeUrl, {
                text: routeHref,
                width: 85,
                height: 85,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            })
        },
        toImage() {
            const that = this
            html2canvas(this.$refs.imageWrapper, {
                backgroundColor: null
            }).then(canvas => {
                let dataURL = canvas.toDataURL('image/png')
                document.querySelector('.share-main').innerHTML =
                    '<img width="100%" src="' + dataURL + '" />'
                setTimeout(() => {
                    that.shareLoading = false
                }, 1000)
            })
        },
        toBase64(url, target) {
            let postData = this.qs.stringify({
                url: url
            })
            this.axios.post('/api/img/base64.json', postData).then(res => {
                const data = res.data
                if (data.status == 1) {
                    this[target] = data.data
                } else {
                    this.commonDialog.alert('提示', data.msg)
                }
            })
        }
    },
    filters: {
        currency(value) {
            return parseFloat(value / 100).toFixed(2)
        }
    }
}
</script>

<style lang="stylus" scoped>
.goods-info-box
    display flex
    align-items center
    height 3.33rem
    padding 0 0.26rem
    background #fff
    .goods-img-box
        width 2.4rem
        height 2.4rem
        overflow hidden
        .goods-img
            width 2.4rem
            height 2.4rem
    .goods-info
        flex 1
        min-width 1px
        margin-left 0.48rem
        .goods-name
            font-size 0.37rem
            color #333
            white-space nowrap
            overflow hidden
            text-overflow ellipsis
        .goods-detail
            margin-top 0.13rem
            font-size 0.32rem
            color #666
            white-space nowrap
            overflow hidden
            text-overflow ellipsis
        .goods-price-box
            display flex
            align-items baseline
            margin-top 0.29rem
            .goods-now-price
                font-size 0.4rem
                color #d7463c
            .goods-normal-price
                margin-left 0.26rem
                font-size 0.32rem
                color #999
.group-buy-rules
    display flex
    align-items baseline
    margin-top 0.18rem
    padding 0.37rem 0.26rem
    background #fff
    .rules-label
        width 1.21rem
        padding 0.1rem 0
        text-align center
        background #d7463c
        font-size 0.32rem
        color #fff
    .rules-detail
        flex 1
        min-width 1px
        margin-left 0.18rem
        font-size 0.32rem
        color #666
        line-height 1.3
.group-info-box
    padding 0.35rem
    text-align center
    background #fff
    margin-top 0.18rem
    .group-people-num
        font-size 0.32rem
        color #333
        span
            color #d7463c
    .group-time
        display flex
        align-items center
        justify-content center
        margin-top 0.33rem
        font-size 0.32rem
        .time-label
            margin 0 0.2rem
            width 0.8rem
            padding 0.1rem 0
            text-align center
            line-height 1
            background #d7463c
            font-size 0.32rem
            color #fff
            border-radius 2px
    .group-tips
        margin-top 0.33rem
        font-size 0.32rem
        color #333
    .group-rules
        margin-top 0.33rem
        font-size 0.32rem
        color #d7463c
    .go-join-btn, .invite-group-btn
        width 2.4rem
        line-height 0.67rem
        text-align center
        background #d7463c
        font-size 0.32rem
        color #fff
        border-radius 3px
        margin 0.33rem auto 0 auto
    .overTime
        background #ededed
.group-join-info
    margin-top 0.18rem
    background #fff
    padding 0 0.26rem
    .group-people-box
        display flex
        align-items center
        justify-content center
        height 2.21rem
        .group-item
            position relative
            width 1.47rem
            height 1.47rem
            .group-item-img
                width 1.47rem
                height 1.47rem
                border-radius 100%
            .group-leader-label
                position absolute
                bottom 0
                left 50%
                width 0.8rem
                line-height 0.4rem
                text-align center
                background #d7463c
                font-size 0.32rem
                color #fff
                padding 0.08rem
                border-radius 10px
            .group-member-label
                position absolute
                bottom 0
                left 50%
                width 1.2rem
                line-height 0.4rem
                text-align center
                background #12d287
                font-size 0.32rem
                color #fff
                padding 0.08rem
                border-radius 10px
        .group-item:nth-child(2)
            margin 0 0.97rem
    .group-create-time
        display flex
        align-items center
        justify-content space-between
        height 1.12rem
        padding 0 0.18rem
        border-top 1px solid #e5e5e5
        .create-time-title
            font-size 0.32rem
            color #999
        .create-time-detail
            font-size 0.32rem
            color #999
    .group-create-rule
        padding 0.17rem 0.18rem
        font-size 0.32rem
        color #999
        line-height 1.3
        border-top 1px solid #e5e5e5
.invite-tips-box
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    background-color rgba(0, 0, 0, 0.7)
    .invite-tips-img
        display block
        width 90%
        margin 0 auto
    .invite-tips-know
        display block
        width 32%
        margin 6.11rem auto 0 auto
.loading-bg
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    padding 5% 10%
    background-color rgba(0, 0, 0, 0.7)
    z-index 9
    display flex
    flex-direction column
    align-items center
    justify-content center
    .loading-img
        width 1rem
        height 1rem
    .loading-tips
        width 100%
        margin-top 0.37rem
        font-size 0.38rem
        color #fff
        text-align center
.share-bg
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    background-color rgba(0, 0, 0, 0.7)
    z-index 9
    display flex
    flex-direction column
    justify-content center
    align-items center
    .share-main
        position relative
        width 300px
        height 501px
        .share-img
            display block
            width 300px
            margin 0 auto
        .share-main-bg
            position absolute
            top 0
            left 0
            width 300px
            height 501px
        .user-info-box
            position absolute
            top 20px
            left 0
            right 70px
            display flex
            align-items center
            padding 0 15px
            .user-img
                width 50px
                height 50px
                border-radius 100%
            .user-info
                flex 1
                margin-left 10px
                .user-name-id
                    font-size 12px
                    color #333
                    .id-color
                        margin-left 10px
                        color #999
                .user-tips
                    margin-top 5px
                    font-size 14px
                    font-weight bold
                    color #ab2023
        .share-img-box
            position absolute
            top 80px
            left 0
            right 0
            text-align center
            .share-img
                width 270px
                height 270px
            .share-tips-img
                position absolute
                left 0
                bottom 0
                width 100%
            .share-tips
                position absolute
                left 256px
                bottom 5px
                font-size 24px
                color #fff
        .share-price-bg
            position absolute
            top 240px
            left 20px
            width 100px
            height 82px
        .share-price
            position absolute
            top 240px
            left 20px
            width 100px
            height 82px
            line-height 70px
            text-align center
            font-size 28px
            color #ab2023
            font-weight bold
            font-style italic
            .share-price-symbol
                font-size 13px
                margin-right 3px
        .qrcode-box
            position absolute
            bottom 35px
            right 20px
            width 85px
            height 85px
    .share-tips
        margin-top 0.37rem
        text-align center
        font-size 0.38rem
        color #fff
    .close-btn
        width 1rem
        height 1rem
</style>

